package Servlets.xzh;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import Bean.Product;
import Bean.UserIndex.Level;
import Util.GokJDBCUtil2;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@WebServlet(name = "UserIndexServlet", urlPatterns = "/UserIndexServlet")
public class UserIndexServlet extends HttpServlet {
    public void init() {
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        int pageSize = 10;
        int currentPage = req.getParameter("currentPage") == null ? 1 : Integer.parseInt(req.getParameter("currentPage"));
        int totalPage = 0;
        boolean haveParmas = false;
        String proname = req.getParameter("proname");
        String originplace = req.getParameter("originplace");
        String levelname = req.getParameter("levelid");
        String minPriceStr = req.getParameter("minPrice");
        String maxPriceStr = req.getParameter("maxPrice");
        Integer minPrice = (minPriceStr == null || minPriceStr.trim().isEmpty()) ? null : Integer.parseInt(minPriceStr.trim());
        Integer maxPrice = (maxPriceStr == null || maxPriceStr.trim().isEmpty()) ? null : Integer.parseInt(maxPriceStr.trim());
        String orderBy = req.getParameter("orderBy") == null || req.getParameter("orderBy").equals("") ? null : req.getParameter("orderBy");
        String orderType = req.getParameter("orderType") == null || req.getParameter("orderType").equals("") ? null : req.getParameter("orderType");

        StringBuilder sql = new StringBuilder("select product.id," +
                "product.proname," +
                "product.price," +
                "product.originplace," +
                "product.categoryid," +
                "tea_category.categoryname," +
                "product.levelid," +
                "product.productionyear," +
                "product.productionmonth," +
                "product.quantity," +
                "product.description," +
                "product.status," +
                "product_level.levelname," +
                "src "+
                " from product," +
                "product_level," +
                "tea_category " +
                "where product.levelid = product_level.id and product.categoryid = tea_category.id  and product.status = 1");
        List<Object> params = new ArrayList<Object>();


        if(proname != null && !proname.isEmpty()) {
            sql.append(" and proname like '%" + proname + "%'");
            haveParmas = true;
        }
        if(levelname != null && !levelname.isEmpty()) {
            sql.append(" and levelname like '%" + levelname + "%'");
            haveParmas = true;
        }
        if(originplace != null && !originplace.isEmpty()) {
            sql.append(" and originplace like '%" + originplace + "%'");
            haveParmas = true;
        }
        if(minPrice != null) {
            sql.append(" and price >= " + minPrice);
            haveParmas = true;
        }
        if(maxPrice != null) {
            sql.append(" and price <= " + maxPrice);
            haveParmas = true;
        }
        if(orderBy != null && !orderBy.isEmpty()) {
            haveParmas = true;
            if(orderType.equals("asc")) {
                sql.append(" order by " + orderBy+" "+orderType);
            }else{
                sql.append(" order by " + orderBy+" "+orderType);
            }
        }
        List<Product> products1 = GokJDBCUtil2.queryAll(sql.toString(), Product.class);
        totalPage = (int) Math.ceil((double) products1.size() / pageSize);
        //分页前算总页数
        sql.append(" limit ?,?");
        if(haveParmas){
            currentPage = 1;
        }
        params.add((currentPage - 1) * pageSize);
        params.add(pageSize);
        List<Product> products = GokJDBCUtil2.queryAll(sql.toString(), Product.class, params.toArray());
        String sql_category = "select levelname from product_level ";
        List<Level> levels = GokJDBCUtil2.queryAll(sql_category, Level.class);
        req.setAttribute("levels", levels);

        req.setAttribute("categorys",levels);
        req.setAttribute("products", products);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("currentPage", currentPage);
        req.setAttribute("proname", proname);
        req.setAttribute("originplace", originplace);
        req.setAttribute("levelname", levelname);
        req.setAttribute("minPrice", minPrice);
        req.setAttribute("maxPrice", maxPrice);
        req.setAttribute("orderBy", orderBy);
        req.setAttribute("orderType", orderType);
        req.getRequestDispatcher("/pages/User_indexPage/user_index.jsp").forward(req, res);


    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String method = req.getMethod();
        try {
            if (method.equals("GET")) {
                this.doGet(req, res);
            }else if (method.equals("POST")) {
                this.doGet(req, res);
            }
            else {
                PrintWriter writer = res.getWriter();
                writer.println("{\"code\":\"400\",\"msg\":\"此方法不允许\"}");
                writer.close();
            }
        } catch (Exception e) {
            log.error("服务器处理请求时发生错误", e);
            PrintWriter writer = res.getWriter();
            writer.println("{\"code\":\"500\",\"msg\":\"服务器处理请求时发生错误\"}");
            writer.close();
        }
    }
    public void destroy() {
    }
}